package com.cloud.controller;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.spi.RegisterableService;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloud.common.SessionManager;
import com.cloud.pojo.Admin;
import com.cloud.result.DataResult;
import com.cloud.result.Result;
import com.cloud.service.AdminService;
import com.cloud.utils.GsonBuilderUtil;
import com.google.gson.Gson;


/**
 *
 * @author Sid
 *
 */

@Controller
@RequestMapping(value="admin")
public class AdminController {
	
	@Autowired
	private AdminService adminService;
	
	/**
	 * 云通讯用户注册功能
	 * @param request
	 * @param response
	 * @param admin
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/register",method = RequestMethod.POST)
	public String register(HttpServletRequest request,HttpServletResponse response,Admin admin){
		Gson gson = GsonBuilderUtil.create();
		Result<Integer> result = new Result<>();
		if(admin != null){
			if(StringUtils.isNotBlank(admin.getUsername()) && StringUtils.isNotBlank(admin.getPassword())){
				try {
					Admin ad = adminService.selectAdminByUsername(admin.getUsername());
					if(ad == null){
						int i = adminService.saveAdmin(admin);
						if(i > 0){
							result.setSuccess(i);
						}else {
							result.setFailure(1, "注册失败");
						}
					}else {
					result.setFailure(1, "该用户已存在!");
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					result.setException(e);
				}
			}else {
				result.setFailure(1, "用户名密码不能为空!");
			}
		}else {
			result.setException("注册参数传递异常");
		}
		
		return gson.toJson(result);
	}
	
	/**
	 * 云通讯用户登陆功能
	 * @param request
	 * @param response
	 * @param admin
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/login")
	public String login(HttpServletRequest request,HttpServletResponse response,Admin admin){
		Gson gson = GsonBuilderUtil.create();
		Result<Admin> result = new Result<>();
		if (admin != null) {
			if(StringUtils.isNotBlank(admin.getUsername()) && StringUtils.isNotBlank(admin.getPassword())){
				try {
					Admin ad = adminService.selectAdminByUsername(admin.getUsername());
					if(ad != null){
						if(admin.getPassword().equals(ad.getPassword())){
//							request.getSession().setAttribute("id", admin.getId());
//		        			request.getSession().setAttribute("admin", admin.getUsername());
//		        			SessionManager.addUser(ad.getId(), request.getSession());
							//创建Cookie  
	        		        Cookie nameCookie=new Cookie("name",URLEncoder.encode(ad.getUsername(),"utf-8"));  
	        		        Cookie idCookie=new Cookie("id",ad.getId()+"");  
	        		          
	        		        //设置Cookie的父路径  
	        		        nameCookie.setPath(request.getContextPath()+"/");  
	        		        idCookie.setPath(request.getContextPath()+"/");  
	        		          
	        		        //获取是否保存Cookie  
//	        		        String rememberMe2=request.getParameter("rememberMe");  
//	        		        if(rememberMe2==null){//不保存Cookie  
//	        		            nameCookie.setMaxAge(0);  
//	        		            pswCookie.setMaxAge(0);  
//	        		        }else{//保存Cookie的时间长度，单位为秒  
	        		            nameCookie.setMaxAge(365*24*60*60);  
	        		            idCookie.setMaxAge(365*24*60*60);  
//	        		        }  
	        		        //加入Cookie到响应头  
	        		        response.addCookie(nameCookie);  
	        		        response.addCookie(idCookie);  
							if(ad.getHardware() == null || ad.getHardware() .equals("")){
								ad.setHardware(admin.getHardware());
								Integer update = adminService.updateHardware(ad);
								result.setSuccess(ad);
							}else if(ad.getHardware() .equals(admin.getHardware())){
								result.setSuccess(ad);
							}else {
								result.setFailure(1, "该账号已在其他设备上绑定");
							}
							
						}else {
							result.setFailure(1, "用户密码不正确");
						}
					}else {
						result.setFailure(1, "该用户不存在");
					}
				} catch (Exception e) {
					result.setException(e);
				}
				
			}else {
				result.setFailure(1, "用户名密码不能为空");
			}
		}else {
			result.setException("登录参数传递异常");
		}
		
		return gson.toJson(result);
	}
	
	@RequestMapping("list")
	@ResponseBody
	public DataResult<Admin> selectAdminList(@RequestParam(value="page",defaultValue="0") Integer page,
			@RequestParam(value="rows",defaultValue="30") Integer rows){
		
		DataResult<Admin> dataResult = adminService.selectAdminList(page,rows);
		
		return dataResult;
	}
	
	/**
	 * 批量解绑
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping("unbundling")
	public Map<String, Object> unbundling(String ids){
		Map<String, Object> data = new HashMap<>();
		try {
			adminService.unbundling(ids);
			data.put("status", "000");
			data.put("msg", "解绑成功!");
			data.put("data", "");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return data;
	}
	
	/**
	 * 新增用户
	 * @param admin
	 * @return
	 */
	@RequestMapping("add")
	@ResponseBody
	public Map<String, Object> adminAdd(Admin admin){
		Map<String, Object> data = new HashMap<>();
		try {
				if(admin != null){
					Admin ad = adminService.selectAdminByUsername(admin.getUsername());
					if(ad != null){
						data.put("status", "002");
						data.put("msg", "该用户已开通过!");
						data.put("data", null);
					}else {
						int i = adminService.saveAdmin(admin);
						if(i > 0){
							data.put("status", "000");
							data.put("msg", "用户开通成功!");
							data.put("data", null);
						}
					}
				}else {
					data.put("status", "001");
					data.put("msg", "新增的用户为空,可能参数异常!");
					data.put("data", null);
				}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return data;
	}
	
	//倒用户资料
	@RequestMapping("test")
	@ResponseBody
	public  Map<String, Object> test(){
		Map<String, Object> data = new HashMap<>();
		try {
			data = adminService.test();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return data;
	}
	
}
